﻿using Avalon.Core.Data;
using Avalon.Core.MVC.Attributes;
using Avalon.Core.MVC.StateBags;
using System;

namespace Avalon.Core.MVC.Actions
{
    [PipelineAction("GetEntitiesAction")]
    public sealed class GetEntitiesAction<TModel> : IPipelineAction where TModel : class, IEntity, new()
    {
        public void Execute(ICollectionBag<TModel> stateBag) 
        {
            try
            {
                IRepository<TModel> lRepository = RepositoryConfig.Initialize<TModel>();
                ((ICollectionBag<TModel>)stateBag).Models = lRepository.Get();
            }
            catch (Exception ex)
            {
                stateBag.Error = new Exception(string.Format("Get entites name: {0}", typeof(TModel).Name), ex);
            }
        }

        public void Execute(IStateBag stateBag)
        {
            Execute((ICollectionBag<TModel>)stateBag);
        }

        public int Index { get; set; }
    }
}